<template>
    <div class="hp100">
        <template  v-if="envStatus == 1 || envStatus == 3">
            <Tabs
                v-if="envStatus == 1"
                :value="currentTab"
                @on-click="changeTab"
                class="environ-tab hp100"
                :class="{ 'full-screen': fullShow }"
            >
                <TabPane
                    v-for="(tab, index) in showCodeUrlList"
                    :key="tab.id"
                    :label="tab.name"
                    :name="tab.id"
                >
                <!-- {{tab.iframeLoaded}} -->
                <!-- && tab.code.cloneStatus === 1 -->
                    <template v-if="tab.jupyter && tab.code && tab.code.cloneStatus === 1">
                        <template v-if="iframeShow">
                            <iframe
                                v-show="iframeLoaded"
                                :id="`codeIframe${tab.id}`"
                                :src="`http://${tab.jupyter.accessUrl}`"
                                width="100%"
                                height="100%"
                                scrolling="none"
                                frameborder="0"
                                @load="loadSuccess(tab)"
                                @error="loadSuccess(tab)"
                            ></iframe>
                            <Spin fix v-show="!iframeLoaded" style="height: 100%">
                                <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                                <div>环境正在加载...</div>
                            </Spin>
                        </template>
                        <div class="wp100 hp100 flex-center flex-column" v-else>
                            <p class="mb10">该浏览器版本不支持直接访问编程环境</p>
                            <h3>
                                请点击<a :href="`http://${tab.jupyter.accessUrl}`" target="_blank">进入环境</a>访问
                            </h3>
                        </div>
                    </template>
                    <template v-else>
                        <div v-if="!tab.code" class="hp100 flex-center">
                            <Button type="info" ghost icon="ios-add" @click="openBindCodeModal()" class="no-radius">绑定代码库</Button>
                        </div>
                        <Spin fix v-if="tab.code && [0,2].includes(tab.code.cloneStatus)" style="height: 100%">
                            <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                            <div>代码拉取中...</div>
                        </Spin>
                        <Button v-if="tab.code && tab.code.cloneStatus === 3" icon="md-add" @click="pullVmCode">重新拉取代码</Button>
                    </template>
                </TabPane>
                <template #extra>
                    <div class="flex extra" v-show="currentCode">
                        <!-- 访问地址：{{ showCodeUrlList.find(item => item.id === currentTab).jupyter.accessUrl }} -->
                        <!-- <Divider type="vertical" /> -->
                        访问地址：<a :href="`http://${currentCodeUrl}`" target="_blank">{{ currentCodeUrl }}</a> 
                        <Divider type="vertical" /> 
                        密码：{{ cipher }} 
                        <!-- 环境状态：{{
                            getEnvStatus(envStatus)
                        }} -->
                        <!-- <Divider type="vertical" /> -->
                        <!-- <span v-if="iframeShow" @click="refresh" class="flex pointer edit-wrapper"
                            ><Icon
                                :size="30"
                                type="ios-refresh"
                                style="height: 21px; margin-top: -6px"
                            />刷新</span
                        > -->
                        <Divider type="vertical" />
                        <span @click="openBindCodeModal(currentCode)" class="flex pointer edit-wrapper ml10" v-if="!disabledAllBtn">
                            <span class="edit mr5"></span>
                            修改代码库绑定
                        </span>
                        <span  v-if="iframeShow"  @click="fullScreen" class="flex pointer screen-wrapper ml10"
                            ><span class="screen mr5"></span
                            >{{ fullShow ? '退出全屏' : '全屏查看' }}</span
                        >
                    </div>
                </template></Tabs
            >
            <NoData v-if="envStatus == 3">
                环境配置失败，请<a size="small" type="primary" ghost class="bold"
                        @click="configContentNetns"
                        >重新配置环境</a
                    >
            </NoData>
        </template>
        <Spin class="flex" v-else-if="envStatus == 0 || envStatus == 2" style="height: 100%;width:100%;">
            <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
            <div>环境正在配置...</div>
        </Spin>
        <CodeModal ref="codeModal" :contentId="contentId" :vmId="currentTab" @ok="getVmCodes"></CodeModal>
    </div>
</template>
<script>
import NoData from '@/components/common/no-data';
import CodeModal from './code.vue'
import { getContentNetns, configContentNetns,getVmCodes,pullVmCode } from '../api/content.js';
import { getVms } from '../api/deploy.js'
import { getUserAgentInfo } from '@/libs/utils';
export default {
    name: 'jupyter',
    components: { NoData,CodeModal },
    inject: ['detailParent'],
    data() {
        return {
            codeUrlList: [],
            currentTab: '',
            noCodeText: '环境配置失败，请重新配置',
            fullShow: false,
            iframeShow: true,
            jupyterVms:[],
            vmCodes:[],
            iframeLoaded:false
        };
    },
    computed: {
        contentDetail() {
            return this.detailParent.contentDetail;
        },
        contentId(){
            return this.contentDetail.id;
        },
        cipher() {
            return this.contentDetail.cipher;
        },
        envStatus() {
            return this.contentDetail.envStatus;//3
        },
        projectId(){
            return this.contentDetail.projectId;
        },
        showCodeUrlList(){
            let _this = this;
            return this.jupyterVms.map(item => {
                return {
                    ...item,
                    jupyter:_this.codeUrlList.find(url => url.deviceId === item.id),
                    code:_this.vmCodes.find(code => code.vmId === item.id)
                }
            })
        },
        currentCode(){
            let codeUrl = this.showCodeUrlList.find(item => item.id === this.currentTab);
            if(codeUrl && codeUrl.code){
                return codeUrl.code
            }else{
                return ''
            }
        },
        currentCodeUrl(){
            let codeUrl = this.showCodeUrlList.find(item => item.id === this.currentTab);
            if(codeUrl && codeUrl.jupyter){
                return codeUrl.jupyter.accessUrl
            }else{
                return ''
            }
        },
        disabledAllBtn(){
            this.detailParent.disabledAllBtn
        }
    },
    watch: {
        envStatus(val) {
            if (val === 1) {
                this.getContentNetns();
                this.getVmCodes();
            }
        },
        projectId(val){
            val && this.getVms();
        },
        currentTab(val){
            this.iframeLoaded = false;
        }
    },
    mounted() {
        if (this.envStatus === 1) {
            this.getContentNetns();
            this.getVmCodes();
        }
        this.projectId && this.getVms();
        //跨域iframe，无法登录
        let version = getUserAgentInfo();
        if (version.type === 'Chrome' && version.version >= 80) {
            this.iframeShow = false;
        }
    },
    beforeDestroy(){
        clearTimeout(this.timeout)
    },
    methods: {
        changeTab(val) {
            this.currentTab = val;
        },
        getVms(){
            let params = {
                pageIndex:1,
                pageSize:100,
                vmType:'DES',
                projectId: this.projectId
            };
            getVms(params).then(({code,data,message}) => {
                if(code === 1){
                    this.jupyterVms = data.items;
                    this.currentTab = this.jupyterVms[0].id;
                }else{
                    this.jupyterVms = [];
                }
            })
        },
        getVmCodes(){
            let params = {contentId:this.$route.query.id};
            getVmCodes(params).then(({code,data,message}) => {
                if(code === 1){
                    this.vmCodes = data;
                    clearTimeout(this.timeout)
                    if(this.vmCodes.some(code => code.cloneStatus == 0  || code.cloneStatus == 2)){
                        this.timeout = setTimeout(() => {
                            this.getVmCodes()
                        },5000)
                    }
                }else{
                    this.vmCodes = [];
                }
            })
        },
        getContentNetns() {
            this.noCodeText = '环境配置失败，请重新配置';
            return new Promise((resolve, reject) => {
                getContentNetns(this.$route.query.id).then(({ code, data, message }) => {
                    if (code === 1) {
                        this.codeUrlList = data;
                    } else {
                        this.noCodeText = message;
                    }
                    resolve();
                });
            });
        },
        pullVmCode(){
            pullVmCode(this.currentTab).then(({code,data,message}) => {
                if(code === 1){
                    this.$Message.info('拉取代码成功');
                }else{
                    this.$Message.error(message);
                }
            })
        },
        configContentNetns() {
            configContentNetns(this.$route.query.id).then(async ({ code, data, message }) => {
                if (code === 1) {
                    this.detailParent.getContentDetail('poll');
                }
            });
        },
        getEnvStatus(status) {
            if (status === 0) {
                return '初始状态';
            } else if (status === 1) {
                return '成功';
            } else if (status === 2) {
                return '准备中';
            } else if (status === 3) {
                return '失败';
            }
        },
        fullScreen() {
            this.fullShow = !this.fullShow;
            // window.openTrain(`http://${url}`, '_blank');
        },
        createVmCode(){
            this.$refs.codeModal.createVmCode();
        },
        openBindCodeModal(data){
            this.$refs.codeModal.showModal(data);
        },
        loadSuccess(tab){
            this.iframeLoaded = true;
        },
        // refresh() {
        //     document.getElementById(this.currentTab).contentWindow.location.reload(true);
        // },
    },
};
</script>
<style scoped>
.environ-tab {
    background: #fff;
}
.environ-tab /deep/ .ivu-tabs-bar {
    margin-bottom: 0;
}
.environ-tab /deep/ .ivu-tabs-tabpane {
    padding: 10px 16px;
}
.environ-tab /deep/ .ivu-tabs-nav .ivu-tabs-tab {
    padding: 11px 16px;
}
.environ-tab /deep/ .ivu-tabs-content {
    height: calc(100% - 42px);
}
.extra {
    position: relative;
    top: 10px;
    right: 10px;
}
.edit,
.screen {
    width: 20px;
    height: 18px;
    background-size: 20px 18px;
    background-repeat: no-repeat;
}
.screen {
    background-image: url('../assets/research/screen.png');
}
.edit {
    background-image: url('../assets/research/editor.png');
}
.icon-wrapper:hover .edit {
    background-image: url('../assets/research/editorh.png');
}
.edit-wrapper:hover,
.screen-wrapper:hover {
    color: #2d8cf0;
}
.screen-wrapper:hover .screen {
    background-image: url('../assets/research/screenh.png');
}
.full-screen .screen {
    background-image: url('../assets/research/screenOut.png');
}
.full-screen .screen-wrapper:hover .screen {
    background-image: url('../assets/research/screenOuth.png');
}
.demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50%  { transform: rotate(180deg);}
    to   { transform: rotate(360deg);}
}
</style>
